package cn.wolfcode.util;

import cn.wolfcode.domain.Employee;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;

public abstract class UserContext {
    public static final String USER_IN_SESSION = "USER_IN_SESSION";
    public static final String EXPRESSION_IN_SESSION = "EXPRESSION_IN_SESSION";

    // 封装获取session的方法
    public static HttpSession getSession() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getRequest().getSession();
    }

    // 封装设置USER_IN_SESSION到session中
    public static void setCurrentUser(Employee employee) {
        getSession().setAttribute(USER_IN_SESSION, employee);
    }

    // 获取USER_IN_SESSION中的employee
    public static Employee getCurrentUser() {
        return (Employee) getSession().getAttribute(USER_IN_SESSION);
    }

    // 封装设置EXPRESSION_IN_SESSION到session中
    public static void setExpression(List<String> expressions) {
        getSession().setAttribute(EXPRESSION_IN_SESSION, expressions);
    }

    // 获取EXPRESSION_IN_SESSION中的expression
    public static List<String> getExpression() {
        return (List<String>) getSession().getAttribute(EXPRESSION_IN_SESSION);
    }

    //设置一个获取主体的方法
    public static Employee getEmployee() {
        return (Employee) SecurityUtils.getSubject().getPrincipal();
    }
}
